<template>
  <div class="setting-editor">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <n-spin size="large" />
      <p class="loading-text">正在加载设定内容...</p>
    </div>
    
    <!-- 空状态 -->
    <div v-else-if="isEmpty && isNew" class="empty-container">
      <n-empty description="暂无设定内容">
        <template #extra>
          <n-button type="primary" @click="handleAddSetting">创建设定</n-button>
        </template>
      </n-empty>
    </div>
    
    <!-- 编辑器内容 -->
    <div v-else class="editor-container">
      <div class="editor-content">
        <!-- 根据当前活动标签页显示对应内容 -->
        <div v-if="activeTab === 'content'" class="editor-pane">
          <div v-if="!isPreviewMode" class="editor-input-container">
            <n-input
              v-model:value="settingContent"
              type="textarea"
              placeholder="请输入设定内容，支持Markdown格式..."
              class="content-editor custom-scrollbar"
              ref="contentEditorRef"
              :disabled="contentLoading"
            />
            <!-- 内容加载遮罩动画 -->
            <div v-if="contentLoading" class="loading-overlay-container">
              <LoadingDots :visible="true" message="正在生成设定内容" />
            </div>
          </div>
          <div v-else class="preview-pane custom-scrollbar" ref="contentPreviewRef">
            <MarkdownRenderer :content="settingContent" />
            <!-- 内容加载遮罩动画 -->
            <div v-if="contentLoading" class="loading-overlay-container">
              <LoadingDots :visible="true" message="正在生成设定内容" />
            </div>
          </div>
        </div>
        
        <!-- 设定详情页内容 -->
        <div v-if="activeTab === 'details'" class="editor-pane">
          <div class="details-form-container">
            <n-form
              ref="detailsFormRef"
              :model="settingDetails"
              label-placement="left"
              label-width="80px"
              require-mark-placement="right-hanging"
              size="medium"
            >
              <n-form-item label="标题" path="title">
                <n-input v-model:value="settingDetails.title" placeholder="请输入设定标题" />
              </n-form-item>
              
              <n-form-item label="标签" path="tags">
                <n-dynamic-tags v-model:value="settingDetails.tags" :max="10" />
              </n-form-item>
              
              <n-form-item label="描述" path="description">
                <n-input
                  v-model:value="settingDetails.description"
                  type="textarea"
                  placeholder="请输入设定描述"
                  :autosize="{ minRows: 3, maxRows: 6 }"
                />
              </n-form-item>
              
              <n-form-item label="重要性" path="importance">
                <n-rate v-model:value="settingDetails.importance" :count="5" />
              </n-form-item>
              
              <n-form-item label="类型" path="type">
                <n-select
                  v-model:value="settingDetails.type"
                  :options="settingTypeOptions"
                  placeholder="请选择设定类型"
                />
              </n-form-item>
            </n-form>
          </div>
        </div>
        
        <!-- 临时便签页内容 -->
        <div v-for="tab in tempTabs" :key="tab.id" v-show="activeTab === tab.id" class="editor-pane">
          <div v-if="!isPreviewMode" class="editor-input-container">
            <n-input
              v-model:value="tab.content"
              type="textarea"
              placeholder="请输入内容，支持Markdown格式..."
              class="content-editor custom-scrollbar"
            />
            <!-- 内容加载遮罩动画 -->
            <div v-if="tab.isLoading" class="loading-overlay-container">
              <LoadingDots :visible="true" message="正在生成内容" />
            </div>
          </div>
          <div v-else class="preview-pane custom-scrollbar">
            <MarkdownRenderer :content="tab.content" />
            <!-- 内容加载遮罩动画 -->
            <div v-if="tab.isLoading" class="loading-overlay-container">
              <LoadingDots :visible="true" message="正在生成内容" />
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 底部标签页和按钮组 -->
    <div class="editor-tabs">
      <n-tabs 
        v-model:value="activeTab" 
        type="line" 
        animated 
        tab-position="bottom" 
        :tab-style="{ minWidth: '80px', maxWidth: '120px', height: '32px' }"
        @close="handleTabClose"
        closable
      >
        <template #suffix>
          <n-space :size="4">
            <n-button @click="togglePreviewMode" :type="isPreviewMode ? 'primary' : 'default'" size="small">
              {{ isPreviewMode ? '编辑' : '预览' }}
            </n-button>
            <n-button @click="copyContent(activeTab)" size="small">
              复制
            </n-button>
            <n-button @click="clearContent(activeTab)" size="small">
              清空
            </n-button>
            <n-button v-if="activeTab === 'content'" @click="contentLoading ? abortGeneration('content') : showGenerateContentDialog()" type="primary" size="small" :disabled="!settingContent.trim()">
              {{ contentLoading ? '处理中...' : '生成内容' }}
            </n-button>
            <n-button @click="addTempTab" size="small">
              添加便签
            </n-button>
            <n-button type="primary" @click="saveSetting" :loading="saving" size="small">
              保存
            </n-button>
          </n-space>
        </template>
        <n-tab-pane name="content" tab="内容">
        </n-tab-pane>
        <n-tab-pane name="details" tab="详情">
        </n-tab-pane>
        <n-tab-pane v-for="tab in tempTabs" :key="tab.id" :name="tab.id" :tab="tab.title" :closable="true">
        </n-tab-pane>
      </n-tabs>
    </div>
    
    <!-- 生成内容对话框 -->
    <GenerateDialog
      v-model:visible="generateContentDialogVisible"
      title="生成设定内容"
      confirm-button-text="生成"
      :loading="generateContentDialogLoading"
      :form="generateContentForm"
      template-category="setting"
      @model-select="handleContentModelSelect"
      @template-select="handleContentTemplateSelect"
      @confirm="handleGenerateContentConfirm"
      @cancel="handleGenerateContentCancel"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import { bookSettingService } from '../services/setting-service'
import { useCurrentBookStore } from '../stores/current-book'
import MarkdownRenderer from '../../shared/components/MarkdownRenderer.vue'
import LoadingDots from '../../shared/components/LoadingDots.vue'
import GenerateDialog from '../components/GenerateDialog.vue'

const route = useRoute()
const router = useRouter()
const message = useMessage()
const currentBookStore = useCurrentBookStore()

// 设定ID
const settingId = ref<string | null>(null)

// 加载状态
const loading = ref(false)
const saving = ref(false)
const contentLoading = ref(false)

// 是否为新建设定
const isNew = computed(() => !settingId.value)

// 是否为空状态
const isEmpty = computed(() => !settingContent.value && !settingDetails.value.title)

// 当前活动标签页
const activeTab = ref('content')

// 临时便签页管理
const tempTabs = ref<Array<{
  id: string
  title: string
  content: string
  isActive: boolean
  isLoading: boolean
}>>([])

// 预览模式
const isPreviewMode = ref(false)

// 设定内容
const settingContent = ref('')

// 设定详情
const settingDetails = ref({
  title: '',
  description: '',
  tags: [] as string[],
  importance: 3,
  type: 'worldview' // 默认类型为世界观
})

// 设定类型选项
const settingTypeOptions = [
  { label: '世界观', value: 'worldview' },
  { label: '角色设定', value: 'character' },
  { label: '情节设定', value: 'plot' },
  { label: '场景设定', value: 'scene' },
  { label: '物品设定', value: 'item' },
  { label: '其他', value: 'other' }
]

// 生成内容对话框
const generateContentDialogVisible = ref(false)
const generateContentDialogLoading = ref(false)
const generateContentForm = ref({
  modelId: '',
  systemPromptId: 13, // 设置默认值
  userPrompt: ''
})

// 引用DOM元素
const contentEditorRef = ref(null)
const contentPreviewRef = ref(null)
const detailsFormRef = ref(null)

// 当前书籍
const currentBook = computed(() => currentBookStore.currentBook)

// 加载设定数据
const loadSetting = async (id: string) => {
  if (!id) return
  
  loading.value = true
  try {
    const response = await bookSettingService.getSettingById(Number(id))
    if (response.code === 0 && response.data) {
      settingContent.value = response.data.content || ''
      settingDetails.value = {
        title: response.data.title || '',
        description: response.data.description || '',
        tags: response.data.tags ? response.data.tags.split(',') : [],
        importance: response.data.importance || 3,
        type: response.data.type || 'worldview'
      }
    } else {
      message.error(response.msg || '加载设定失败')
    }
  } catch (error) {
    console.error('加载设定失败:', error)
    message.error('加载设定失败')
  } finally {
    loading.value = false
  }
}

// 保存设定
const saveSetting = async () => {
  if (!currentBook.value) {
    message.error('请先选择一本书籍')
    return
  }
  
  // 验证必填字段
  if (!settingDetails.value.title.trim()) {
    message.error('请输入设定标题')
    activeTab.value = 'details'
    return
  }
  
  saving.value = true
  try {
    const settingData = {
      id: settingId.value ? Number(settingId.value) : undefined,
      title: settingDetails.value.title,
      content: settingContent.value,
      description: settingDetails.value.description || '',
      tags: settingDetails.value.tags.join(','),
      importance: settingDetails.value.importance || 3,
      type: settingDetails.value.type || 'worldview',
      bookId: currentBook.value.id
    }
    
    let response
    if (isNew.value) {
      // 创建新设定
      response = await bookSettingService.createSetting(settingData)
    } else {
      // 更新现有设定
      response = await bookSettingService.updateSetting(settingData)
    }
    
    if (response.code === 0) {
      message.success(isNew.value ? '设定创建成功' : '设定更新成功')
      
      // 如果是新建设定，更新URL
      if (isNew.value && response.data && response.data.id) {
        settingId.value = String(response.data.id)
        router.replace(`/books/workspace/${currentBook.value.id}/setting/${response.data.id}`)
      }
    } else {
      message.error(response.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存设定失败:', error)
    message.error('保存设定失败')
  } finally {
    saving.value = false
  }
}

// 创建新设定
const handleAddSetting = () => {
  settingId.value = null
  settingContent.value = ''
  settingDetails.value = {
    title: '新设定',
    description: '',
    tags: [],
    importance: 3,
    type: 'worldview'
  }
  activeTab.value = 'content'
}

// 切换预览模式
const togglePreviewMode = () => {
  isPreviewMode.value = !isPreviewMode.value
}

// 复制内容
const copyContent = async (tabName: string) => {
  let contentToCopy = ''
  
  if (tabName === 'content') {
    contentToCopy = settingContent.value
  } else if (tabName === 'details') {
    // 将详情转换为文本格式
    contentToCopy = `标题: ${settingDetails.value.title}\n描述: ${settingDetails.value.description}\n标签: ${settingDetails.value.tags.join(', ')}\n重要性: ${settingDetails.value.importance}\n类型: ${settingTypeOptions.find(opt => opt.value === settingDetails.value.type)?.label || settingDetails.value.type}`
  } else {
    // 临时便签
    const tab = tempTabs.value.find(t => t.id === tabName)
    if (tab) {
      contentToCopy = tab.content
    }
  }
  
  try {
    await navigator.clipboard.writeText(contentToCopy)
    message.success('内容已复制到剪贴板')
  } catch (err) {
    message.error('复制失败，请手动复制')
  }
}

// 清空内容
const clearContent = (tabName: string) => {
  if (tabName === 'content') {
    settingContent.value = ''
  } else if (tabName === 'details') {
    settingDetails.value = {
      title: '',
      description: '',
      tags: [],
      importance: 3,
      type: 'worldview'
    }
  } else {
    // 临时便签
    const tab = tempTabs.value.find(t => t.id === tabName)
    if (tab) {
      tab.content = ''
    }
  }
  message.success('内容已清空')
}

// 添加临时便签
const addTempTab = () => {
  const tabId = `temp-${Date.now()}`
  const tabIndex = tempTabs.value.length + 1
  tempTabs.value.push({
    id: tabId,
    title: `便签 ${tabIndex}`,
    content: '',
    isActive: true,
    isLoading: false
  })
  activeTab.value = tabId
}

// 关闭标签页
const handleTabClose = (tabName: string) => {
  const index = tempTabs.value.findIndex(tab => tab.id === tabName)
  if (index !== -1) {
    tempTabs.value.splice(index, 1)
    if (activeTab.value === tabName) {
      activeTab.value = 'content'
    }
  }
}

// 生成内容相关方法
const showGenerateContentDialog = () => {
  generateContentDialogVisible.value = true
}

const handleContentModelSelect = (modelId: string) => {
  generateContentForm.value.modelId = modelId
}

const handleContentTemplateSelect = (template: any) => {
  if (template) {
    generateContentForm.value.systemPromptId = template.id
  }
}

const handleGenerateContentConfirm = async () => {
  if (!generateContentForm.value.modelId) {
    message.error('请选择模型')
    return
  }

  if (!generateContentForm.value.systemPromptId) {
    message.error('请选择模板')
    return
  }

  if (!generateContentForm.value.userPrompt.trim()) {
    message.error('请输入提示词')
    return
  }

  generateContentDialogLoading.value = true
  contentLoading.value = true

  try {
    // 这里应该调用AI生成内容的API
    // const response = await generateContentAPI(generateContentForm.value)
    // 模拟生成过程
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 模拟生成的内容
    const generatedContent = `这是根据您的提示词生成的设定内容：\n\n${generateContentForm.value.userPrompt}\n\n这里是根据设定类型和重要性生成的详细内容...`
    
    settingContent.value = generatedContent
    generateContentDialogVisible.value = false
    message.success('内容生成成功')
  } catch (error) {
    console.error('生成内容失败:', error)
    message.error('生成内容失败')
  } finally {
    generateContentDialogLoading.value = false
    contentLoading.value = false
  }
}

const handleGenerateContentCancel = () => {
  generateContentDialogVisible.value = false
}

const abortGeneration = (type: string) => {
  if (type === 'content') {
    contentLoading.value = false
    message.info('已取消生成')
  }
}

// 监听路由参数变化
watch(
  () => route.params.settingId,
  (newId) => {
    if (newId && typeof newId === 'string') {
      settingId.value = newId
      loadSetting(newId)
    } else {
      // 没有ID，视为新建设定
      handleAddSetting()
    }
  },
  { immediate: true }
)

// 页面加载时处理
onMounted(() => {
  // 从路由参数获取设定ID
  const id = route.params.settingId
  if (id && typeof id === 'string') {
    settingId.value = id
    loadSetting(id)
  } else {
    // 没有ID，视为新建设定
    handleAddSetting()
  }
})
</script>

<style scoped>
.setting-editor {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #ffffff;
  overflow: hidden;
}

.loading-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  gap: 16px;
}

.loading-text {
  color: #666;
  font-size: 14px;
}

.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.editor-container {
  display: flex;
  flex-direction: column;
  height: calc(100% - 34px);
  flex: 1;
  overflow: hidden;
}

.editor-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.editor-pane {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.editor-input-container {
  position: relative;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.content-editor {
  flex: 1;
  height: 100%;
  min-height: 300px;
  border-radius: 6px;
  padding: 16px;
  font-size: 14px;
  line-height: 1.6;
  resize: none;
  outline: none;
  border: 1px solid #e0e0e6;
  transition: border-color 0.3s;
}

.content-editor:focus {
  border-color: #18a058;
}

.preview-pane {
  flex: 1;
  padding: 16px;
  border-radius: 6px;
  background-color: #fafafa;
  border: 1px solid #e0e0e6;
  overflow-y: auto;
}

.details-form-container {
  padding: 16px;
  height: 100%;
  overflow-y: auto;
}

.loading-overlay-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 6px;
  z-index: 10;
}

.editor-tabs {
  display: flex;
  flex-direction: column;
  height: 34px;
  border-top: 1px solid #e0e0e6;
}

.custom-scrollbar {
  scrollbar-width: thin;
  scrollbar-color: #ccc transparent;
}

.custom-scrollbar::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.custom-scrollbar::-webkit-scrollbar-track {
  background: transparent;
}

.custom-scrollbar::-webkit-scrollbar-thumb {
  background-color: #ccc;
  border-radius: 3px;
}

.custom-scrollbar::-webkit-scrollbar-thumb:hover {
  background-color: #999;
}
</style>